import pygame

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load('./assets/images/player.png').convert_alpha()
        self.rect = self.image.get_rect()

    def update(self, obstacles, ground_tiles):
        # Add player movement logic here
        keys = pygame.key.get_pressed()
        new_rect = self.rect.copy()

        if keys[pygame.K_LEFT] or keys[pygame.K_a]:
            new_rect.x -= 5
        if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
            new_rect.x += 5
        if keys[pygame.K_UP] or keys[pygame.K_w]:
            new_rect.y -= 5
        if keys[pygame.K_DOWN] or keys[pygame.K_s]:
            new_rect.y += 5

        # Check for collisions with obstacles
        if not any(new_rect.colliderect(obstacle.collision_rect) for obstacle in obstacles) and  \
                not any(new_rect.colliderect(ground_tile.rect) and not ground_tile.walkable for ground_tile in ground_tiles) and  \
                any(new_rect.colliderect(ground_tile.rect) for ground_tile in ground_tiles):
            self.rect = new_rect

class Obstacle(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.Surface((64, 64))
        self.rect = self.image.get_rect()
        self.collision_rect = self.image.get_rect()
        self.rect.topleft = (x, y)
        self.collision_rect.topleft = (x, y)

class TileCursor(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.image.load('./assets/images/tile_cursor.png')
        self.rect = self.image.get_rect()
        self.rect.topleft = (x, y)

class ObstacleTile(Obstacle):
    def __init__(self, tiles, x, y, ident):
        super().__init__(x, y)
        self.change_type(tiles, ident)

    def change_type(self, tiles, ident):
        self.image = tiles[ident]['image']['surface'].convert_alpha()
        self.collision_rect.x += tiles[ident]['collision']['position'][0]
        self.collision_rect.y += tiles[ident]['collision']['position'][1]
        self.collision_rect.width = tiles[ident]['collision']['size'][0]
        self.collision_rect.height = tiles[ident]['collision']['size'][1]
        self.ident = ident

class GroundTile(Obstacle):
    def __init__(self, tiles, x, y, ident):
        super().__init__(x, y)
        self.change_type(tiles, ident)

    def change_type(self, tiles, ident):
        self.image = tiles[ident]['image']['surface'].convert_alpha()
        self.walkable = tiles[ident]['walkable']
        self.ident = ident

class CropTile(ObstacleTile):
    def __init__(self, tiles, x, y, ident):
        super().__init__(tiles, x, y, ident)
